package com.jeecg.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PropertiesLoaderUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Collection;
import java.util.Map;
import java.util.Properties;

/**
 * 维护工具类
 * 
 * @author xiaoyu
 * 
 */
public class AssertUtil {
	
	private static Logger logger = LoggerFactory.getLogger(AssertUtil.class);

	private static Resource resource = null;
    private static Properties props = null;
	
	public static <T> boolean isEmpty(T[] obj) {
		return (null == obj) || (0 == obj.length);
	}

	public static boolean isEmpty(Object obj) {
		if (null == obj)
			return true;
		if ((obj instanceof String))
			return isNullEmpty((String) obj);
		if ((obj instanceof Number)) {
			return false;
		}
		return false;
	}

	public static boolean isEmpty(Collection obj) {
		return (null == obj) || (obj.isEmpty());
	}

	public static boolean isEmpty(Map obj) {
		return (null == obj) || (obj.isEmpty());
	}

	public static boolean isNullEmpty(String text) {
		if (null == text)
			return true;
		if (0 == text.trim().length()) {
			return true;
		}
		return false;
	}
	
	/**
	 * GBK转UTF-8
	 * @param msg
	 * @return
	 * @creator xiaoyu
	 * @createTime 2017-3-16 下午5:41:18
	 */
	public static String gbkToUtf8(String msg) {
		String str = null;
		try {
			str = new String(msg.getBytes("GBK"), "UTF-8");
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return str;
	}
	
	/**
	 * 获取properties文件
	 * @param filePath 文件路径
	 * @return
	 * @creator xiaoyu
	 * @createTime 2017-3-28 上午10:13:20
	 */
	public static Properties getProperties(String filePath) {
		synchronized (AssertUtil.class) {
			if (resource == null || props == null) {
				resource = new ClassPathResource(filePath);
				try {
					props = PropertiesLoaderUtils.loadProperties(resource);
				} catch (IOException e) {
					logger.error("读取文件错误：" + e.getMessage());
				}
			}
		}
		return props;
	}

	/**
     * 获取系统prop
	 * @param key
     * @return
     */
	public static String getPropValue(String key) {
		Properties pro = getProperties("/sysConfig.properties");
		return pro.getProperty(key);
	}
	
	/**
	 * 获取request对象
	 * @return
	 * @creator xiaoyu
	 * @createTime 2017-4-12 下午5:37:24
	 */
	public static HttpServletRequest getRequest() {
		return ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();
	}
	
}
